<template>
  <div class="my-items-container">
    <!-- 页面标题栏 -->
    <div class="header-bar">
      <div class="header-left" @click="router.back()">
        <i class="fas fa-arrow-left"></i>
      </div>
      <div class="header-title">我的发布</div>
    </div>

    <!-- 标签页 -->
    <div class="tab-bar">
      <div
          v-for="tab in tabs"
          :key="tab.value"
          :class="['tab', { active: activeTab === tab.value }]"
          @click="switchTab(tab.value)"
      >
        {{ tab.label }}
      </div>
    </div>

    <!-- 物品列表 -->
    <div class="items-list">
      <div v-if="loading" class="loading">
        <i class="fas fa-spinner fa-spin"></i>
        <span>加载中...</span>
      </div>

      <div v-else-if="items.length === 0" class="empty-state">
        <i class="fas fa-box-open"></i>
        <p>{{ getEmptyStateMessage }}</p>
        <el-button type="primary" @click="addNewItem">
          发布新物品
        </el-button>
      </div>

      <div v-else>
        <div class="debug-info">
          找到 {{ filteredItems.length }} 个物品
        </div>

        <div
            v-for="item in filteredItems"
            :key="item.id"
            class="item-card"
            @click="viewItemDetail(item)"
        >
          <div class="item-image">
            <img :src="item.images[0] || 'https://via.placeholder.com/100'" :alt="item.name" />
            <div :class="['item-status', getStatusClass(item.status)]">
              {{ getStatusText(item.status) }}
            </div>
          </div>
          <div class="item-info">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-description">{{ item.title }}</div>
            <div class="item-meta">
              <span class="meta-points">{{ item.points }}积分/天</span>
              <span class="meta-views">{{ item.views }}浏览</span>
              <span class="meta-date">{{ formatDate(item.createdAt) }}</span>
            </div>
          </div>
          <div class="item-actions">
            <el-button
                v-if="item.status === 1"
                size="small"
                @click.stop="editItem(item)"
            >
              编辑
            </el-button>
            <el-button
                v-if="item.status === 1"
                type="danger"
                size="small"
                @click.stop="offlineItem(item)"
            >
              下架
            </el-button>
            <el-button
                v-if="item.status === 2"
                type="primary"
                size="small"
                @click.stop="relistItem(item)"
            >
              重新上架
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 自定义确认对话框 -->
    <el-dialog
        v-model="confirmDialog.visible"
        :title="confirmDialog.title"
        width="80%"
        custom-class="custom-confirm-dialog"
        :show-close="false"
        center
    >
      <div class="confirm-content">
        <i :class="confirmDialog.icon"></i>
        <p>{{ confirmDialog.message }}</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="confirmDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmDialog.confirmAction">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 编辑物品对话框 -->
  <el-dialog
      v-model="editDialogVisible"
      title="编辑物品信息"
      width="90%"
      :close-on-click-modal="false"
  >
    <el-form :model="editingItem" label-width="80px">
      <el-form-item label="物品名称">
        <el-input v-model="editingItem.title" placeholder="请输入物品名称" />
      </el-form-item>

      <el-form-item label="描述">
        <el-input
            v-model="editingItem.description"
            type="textarea"
            :rows="3"
            placeholder="请输入物品描述"
        />
      </el-form-item>

      <el-form-item label="类型">
        <el-radio-group v-model="editingItem.type">
          <el-radio :label="1">出售</el-radio>
          <el-radio :label="2">出租</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="价格/积分">
        <el-input-number
            v-model="editingItem.price"
            :min="0"
            :step="1"
            placeholder="请输入价格或积分"
        />
      </el-form-item>

      <el-form-item v-if="editingItem.type === 2" label="出租方式">
        <el-select v-model="editingItem.rentType" placeholder="请选择出租方式">
          <el-option :value="1" label="按天出租" />
          <el-option :value="2" label="按周出租" />
          <el-option :value="3" label="按月出租" />
        </el-select>
      </el-form-item>

      <el-form-item v-if="editingItem.type === 2" label="出租数量">
        <el-input-number
            v-model="editingItem.rentCount"
            :min="1"
            :step="1"
            placeholder="出租天数/周数/月数"
        />
      </el-form-item>

      <el-form-item label="图片URL">
        <el-input
            v-model="editingItem.images"
            placeholder="请输入图片URL（多个用逗号分隔）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveEditedItem">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from "@/utils/axios.ts";
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const activeTab = ref(0) // 使用数字类型：0-全部, 1-上架, 2-下架
const loading = ref(false)
const items = ref([])
const userId = ref(null)

// 标签页数据 - 使用数字类型
const tabs = reactive([
  { label: '全部', value: 0 },
  { label: '上架', value: 1 },
  { label: '已下架', value: 2 }
])

// 新增响应式数据
const editDialogVisible = ref(false)
const editingItem = ref({
  itemId: null,
  title: '',
  description: '',
  type: 1, // 1:出售, 2:出租
  price: 0,
  rentType: 1, // 1:按天, 2:按周, 3:按月
  rentCount: 1,
  images: null,
})

// 自定义确认对话框
const confirmDialog = reactive({
  visible: false,
  title: '',
  message: '',
  icon: '',
  confirmAction: () => {}
})

// 计算属性：根据标签过滤物品
const filteredItems = computed(() => {
  if (activeTab.value === 0) {
    return items.value
  }
  return items.value.filter(item => item.status === activeTab.value)
})

// 计算属性：空状态消息
const getEmptyStateMessage = computed(() => {
  switch (activeTab.value) {
    case 1:
      return '暂无上架物品'
    case 2:
      return '暂无已下架物品'
    default:
      return '暂无发布物品'
  }
})

// 初始化数据
const init = async () => {
  loading.value = true

  if (!userId.value) {
    ElMessage.error('用户ID未获取到')
    loading.value = false
    return
  }

  try {
    const response = await axios.get(
        `/api/userItems/getItemsListByUid/${userId.value}/${activeTab.value}`
    )

    // 1. 处理空数据情况
    if (!response.data || response.data.length === 0) {
      items.value = []
      console.log('未查询到物品数据')
      return
    }

    // 2. 安全处理数据转换
    const processedItems = response.data.map(item => {
      const processedItem = { ...item }

      // 处理 images
      try {
        processedItem.images = item.images && typeof item.images === 'string'
            ? JSON.parse(item.images)
            : []
      } catch (error) {
        console.error('解析images失败:', error)
        processedItem.images = []
      }

      // 处理 tag
      try {
        processedItem.tag = item.tag && typeof item.tag === 'string'
            ? JSON.parse(item.tag)
            : []
      } catch (error) {
        console.error('解析tag失败:', error)
        processedItem.tag = []
      }

      return processedItem
    })

    items.value = processedItems
    console.log('成功获取物品列表，数量:', items.value.length)

  } catch (error) {
    console.error('获取发布列表失败:', error)

    // 更友好的错误提示
    const errorMsg = error.response?.data?.message ||
        error.message ||
        '请求失败，请稍后重试'

    ElMessage.error(`获取发布列表失败: ${errorMsg}`)
  } finally {
    loading.value = false
  }
}

// 切换标签页
const switchTab = (tabValue) => {
  activeTab.value = tabValue
  console.log("切换标签到:", tabValue)
  // 切换标签时重新加载数据
  init()
}

// 获取状态样式类 - 使用数字类型
const getStatusClass = (status) => {
  return {
    1: 'status-available', // 上架
    2: 'status-offline'    // 下架
  }[status] || ''
}

// 获取状态文本 - 使用数字类型
const getStatusText = (status) => {
  return {
    1: '上架',   // 上架
    2: '已下架'  // 下架
  }[status] || ''
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知日期'

  try {
    const date = new Date(dateString)
    return `${date.getMonth() + 1}月${date.getDate()}日`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return '无效日期'
  }
}

// 查看物品详情
// 查看物品详情
const viewItemDetail = (item) => {
  console.log('查看物品详情:', item.itemId)
  let id = item.itemId
  // 传递状态信息到详情页面
  router.push({
    path: `/myItemDetail/${id}`,
    query: { status: item.status } // 添加状态参数
  })
}

// 编辑物品
const editItem = async (item) => {
  try {
    // 获取物品详情
    const response = await axios.get(`/api/userItems/getItemById/${item.itemId}`)

    if (response.code === 200 && response.data) {
      // 填充编辑表单
      editingItem.value = {
        itemId: response.data.itemId,
        title: response.data.title,
        description: response.data.description,
        type: response.data.type,
        price: response.data.price,
        rentType: response.data.rentType || 1,
        rentCount: response.data.rentCount || 1,
        images: response.data.images || '',
      }

      // 显示编辑对话框
      editDialogVisible.value = true
    } else {
      ElMessage.error('获取物品详情失败')
    }
  } catch (error) {
    console.error('获取物品详情失败:', error)
    ElMessage.error('获取物品详情失败')
  }
}

const saveEditedItem = async () => {
  try {
    // 验证必填字段
    if (!editingItem.value.title || !editingItem.value.description) {
      ElMessage.warning('请填写物品名称和描述')
      return
    }

    // 准备提交数据
    const submitData = {
      itemId: editingItem.value.itemId,
      title: editingItem.value.title,
      description: editingItem.value.description,
      type: editingItem.value.type,
      price: editingItem.value.price,
      images: editingItem.value.images,
    }

    // 如果是出租类型，添加出租相关字段
    if (editingItem.value.type === 2) {
      submitData.rentType = editingItem.value.rentType
      submitData.rentCount = editingItem.value.rentCount
    }

    // 调用编辑接口
    const response = await axios.post('/api/userItems/editItem', submitData)

    if (response.code === 200 && response.data) {
      ElMessage.success('物品信息更新成功')
      editDialogVisible.value = false
      init() // 重新加载列表
    } else {
      ElMessage.error('更新物品信息失败')
    }
  } catch (error) {
    console.error('更新物品信息失败:', error)
    ElMessage.error('更新物品信息失败')
  }
}

// 重新上架物品
const relistItem = (item) => {
  confirmDialog.title = '重新上架确认'
  confirmDialog.message = '确定要重新上架这个物品吗？'
  confirmDialog.icon = 'fas fa-arrow-up-circle'
  confirmDialog.confirmAction = async () => {
    try {
      console.log("item的id：", item.itemId)
      const response = await axios.post(`/api/userItems/changeStatus/up/${item.itemId}/${activeTab.value}`)
      if (response.code === 200) {
        ElMessage.success('物品重新上架成功')
        init() // 重新加载数据
      }
    } catch (error) {
      console.error('重新上架失败:', error)
      ElMessage.error('重新上架失败')
    } finally {
      confirmDialog.visible = false
    }
  }
  confirmDialog.visible = true
}

// 下架物品
const offlineItem = (item) => {
  confirmDialog.title = '下架确认'
  confirmDialog.message = '确定要下架这个物品吗？'
  confirmDialog.icon = 'fas fa-arrow-down-circle'
  confirmDialog.confirmAction = async () => {
    try {
      const response = await axios.post(`/api/userItems/changeStatus/down/${item.itemId}/${activeTab.value}`)
      if (response.code === 200) {
        ElMessage.success('物品下架成功')
        init() // 重新加载数据
      }
    } catch (error) {
      console.error('下架失败:', error)
      ElMessage.error('下架失败')
    } finally {
      confirmDialog.visible = false
    }
  }
  confirmDialog.visible = true
}

// 发布新物品
const addNewItem = () => {
  console.log('发布新物品')
  router.push('/publishItem')
}

onMounted(() => {
  // 获取用户信息
  axios.post("/api/users/getUserInfo")
      .then(res => {
        console.log("用户信息:", res.data)
        // 正确赋值方式
        userId.value = res.data.userId;
        console.log("userId", userId.value)
        // 然后调用 init
        init();
      })
      .catch(error => {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
      })
})
</script>

<style scoped>
.my-items-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 标题栏样式 */
.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: white;
  padding: 15px 20px;
  font-size: 18px;
  font-weight: bold;
}

.header-left, .header-right {
  width: 40px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.header-right {
  justify-content: flex-end;
}

.header-title {
  flex: 1;
  text-align: center;
}

/* 标签页样式 */
.tab-bar {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #eee;
}

.tab {
  flex: 1;
  padding: 15px 0;
  text-align: center;
  cursor: pointer;
  position: relative;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
}

.tab.active {
  color: #6a11cb;
  font-weight: bold;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20%;
  right: 20%;
  height: 3px;
  background-color: #6a11cb;
  border-radius: 3px;
}

/* 物品列表样式 */
.items-list {
  padding: 15px;
  min-height: 300px; /* 确保有足够空间显示内容 */
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #666;
}

.loading i {
  font-size: 24px;
  margin-bottom: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  color: #999;
  text-align: center;
}

.empty-state i {
  font-size: 60px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-state p {
  margin-bottom: 20px;
  font-size: 16px;
}

.debug-info {
  padding: 10px;
  background-color: #f0f0f0;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #666;
}

/* 物品卡片样式 */
.item-card {
  display: flex;
  background-color: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.item-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.item-image {
  position: relative;
  width: 100px;
  height: 100px;
  margin-right: 15px;
  flex-shrink: 0;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  background-color: #f5f5f5; /* 添加背景色 */
}

.item-status {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-available {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-offline {
  background-color: #f5f5f5;
  color: #999;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.item-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-meta {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.meta-points {
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 15px;
}

.meta-views, .meta-date {
  margin-right: 15px;
}

.item-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 5px;
}

/* 发布按钮样式 */
.fab-button {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  box-shadow: 0 4px 15px rgba(106, 17, 203, 0.4);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  z-index: 1000;
}

.fab-button:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(106, 17, 203, 0.6);
}
</style>

<style>
/* 自定义确认对话框样式 */
.custom-confirm-dialog {
  border-radius: 16px !important;
  text-align: center;
}

.custom-confirm-dialog .el-dialog__header {
  padding: 20px 20px 10px;
  border-bottom: none;
}

.custom-confirm-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.custom-confirm-dialog .el-dialog__body {
  padding: 20px;
}

.confirm-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.confirm-content i {
  font-size: 48px;
  margin-bottom: 20px;
  color: #6a11cb;
}

.confirm-content p {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
}

.custom-confirm-dialog .el-dialog__footer {
  padding: 10px 20px 20px;
  border-top: none;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.dialog-footer .el-button {
  min-width: 100px;
  border-radius: 8px;
}
</style>